let components = require.context('../pages', true, /\.js$/, 'sync')

let paths = components.keys()//获得了所有引入文件的地址
let routes = paths.map(path => {
    let component = components(path).default
    // path = path.substr(1).replace(/\/\w+\.js$/, "") //最好用index匹配
    path = path.substr(1).replace(/(\/index\.js|\.js)$/, "") //最好用index匹配
    return {
        path,
        component
    }
})

//实现扁平化数据转换成树形图算法
function convertTree(routes) {
    if (!Array.isArray(routes) || !routes.length) {
        return
    }
    let treeArr = []
    routes.forEach(route => {
        let compareRoute = route.path.substr(1).split("/")
        // console.log(compareRoute)
        if (compareRoute.length === 1) { //说明是根路由
            route.id = compareRoute[0]
        } else {
            let id = compareRoute.reduce((id, item) => {
                return id += item
            })
            route.id = id;
            compareRoute.pop();
            route.parent_id = compareRoute.join("")
        }
    })


    routes.forEach(item => {
        if (item.parent_id) {
            //去找父节点
            let target = routes.find(v => v.id === item.parent_id);
            if (!target.children) {
                target.children = []
            }
            target.children.push(item)
            // console.log(target)   
        } else {
            //说明是根节点
            treeArr.push(item)
        }

    })

    return treeArr;
}

export default convertTree(routes)


